# 用于拉取RNOH框架代码，首次构建benchmark项目

SAMPLE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/

cd $SAMPLE_DIR/../

# 拉取RNOH项目代码
if [ -d "ohos_react_native" ]; then
    echo "ohos_react_native already exists, skip cloning rnoh code"
else
    git clone https://gitee.com/openharmony-sig/ohos_react_native
fi

cd ohos_react_native

# 拉取第三方依赖，这一命令可能失败，重试直到没有任何输出
git submodule update --init --recursive --jobs=8

max_attempts=16
attempt=0
success=0
while [ $attempt -le $max_attempts ]; do
    attempt=$((attempt + 1))
    git submodule update --init --recursive --jobs=8
    if [ $? -eq 0 ]; then
        success=1
        break
    fi
done

# 拉取三方依赖失败，退出
if [ $success -eq 0 ]; then
    echo -e "\n\n\n\n\n\n\n\n\n\n  fetch git submodule failed, check ur network and try again  \n\n\n\n\n\n\n\n\n\n"
    exit 1
fi

# 删除老的打包产物，防止后面依赖到之前打包出来的npm包。首次构建这个没必要
rm react-native-harmony-cli/rnoh-react-native-harmony-cli-*.tgz react-native-harmony-sample-package/react-native-harmony-sample-package-*.tgz react-native-harmony/rnoh-react-native-harmony-*.tgz

cd react-native-harmony-cli
npm i && npm pack
cd ..

# cd react-native-harmony
# npm i && npm pack
# cd ..

cd react-native-harmony-sample-package
npm i && npm pack
cd ..

cd tester
npm run i

# 设置 RNOH_C_API_ARCH 环境变量
if [ "${RNOH_C_API_ARCH:-0}" -ne 1 ]; then
    export RNOH_C_API_ARCH=1 # 当前session
    if [ -f "$HOME/.bashrc" ]; then
        echo -e "\n\n# RNOH use capi architecture flag \nexport RNOH_C_API_ARCH=1\n" >> $HOME/.bashrc # 持久化
    fi
    if [ -f "$HOME/.zshrc" ]; then
        echo -e "\n\n# RNOH use capi architecture flag \nexport RNOH_C_API_ARCH=1\n" >> $HOME/.zshrc # 持久化
    fi
fi

# 构建框架源码har包
cd harmony
hvigorw --sync -p product=default --analyze=false --parallel --incremental --daemon &&
hvigorw --mode module -p product=default -p module=react_native_openharmony@default -p buildMode=release assembleHar --error --analyze=false --parallel --incremental --daemon

# 构建benchmark项目
cd $SAMPLE_DIR

# 安装依赖
npm i

# 打包benchmark前端代码
npm run prod:hbc

# 安装 rnoh har 包
cd harmony
ohpm i

hvigorw --sync -p product=default --analyze=false --parallel --incremental --daemon
hvigorw --mode module -p module=entry@default -p product=default -p buildMode=release -p requiredDeviceType=phone assembleHap --analyze=false --parallel --incremental --daemon
hdc install entry/build/default/outputs/default/entry-default-signed.hap
